package com.stars.easyms.mq.properties;

import com.stars.easyms.base.constant.EasyMsCommonConstants;
import com.stars.easyms.mq.enums.MQ;
import com.stars.easyms.mq.exception.EasyMsMQException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * EasyMs的MQ属性配置类
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
@Data
@ConfigurationProperties(prefix = EasyMsMQProperties.PREFIX)
public class EasyMsMQProperties {

    public static final String PREFIX = EasyMsCommonConstants.EASY_MS_PROPERTIES_PREFIX + "mq";

    /**
     * 是否激活mq
     */
    private Boolean enabled;

    /**
     * 系统ID，优先与spring.application.name
     * @since 1.3.3
     */
    private String applicationId;

    /**
     * 当前激活的MQ类型
     */
    private MQ active = MQ.ROCKETMQ;

    /**
     * 是否异步加载，默认异步加载
     */
    private boolean asyncLoad = true;

    /**
     * MQ扫描的路径
     */
    private List<String> basePackage;

    private ActiveMQ activemq = new ActiveMQ();

    private RocketMQ rocketmq = new RocketMQ();

    private final Map<String, String> key = new HashMap<>(8);

    @Data
    public static class ActiveMQ {

        /**
         * activeMQ的连接地址
         */
        private String brokerUrl;

        /**
         * activeMQ的登录用户名
         */
        private String user;

        /**
         * activeMQ的登录密码
         */
        private String password;

        /**
         * 是否允许activeMQ非持久化，非持久化速度变快，但有丢数据风险
         */
        private boolean allowNonPersistent;

    }

    @Data
    public static class RocketMQ {

        /**
         * rocketMQ的连接地址
         */
        private String nameServer;

    }

    public boolean isEnabled() {
        return enabled != null && enabled;
    }

    public void check() {
        if (enabled != null && !enabled) {
            return;
        }

        if (active == MQ.ACTIVEMQ) {
            if (StringUtils.isBlank(activemq.getBrokerUrl()) || StringUtils.isBlank(activemq.getUser())
                    || StringUtils.isBlank(activemq.getPassword())) {
                if (enabled != null) {
                    throw new EasyMsMQException("Please configure the active mq with [{}.activemq]!", PREFIX);
                }
                enabled = false;
            } else {
                enabled = true;
            }
        } else if (active == MQ.ROCKETMQ) {
            if (StringUtils.isBlank(rocketmq.getNameServer())) {
                if (enabled != null) {
                    throw new EasyMsMQException("Please configure the rocket mq with [{}.rocketmq.name-server]!", PREFIX);
                }
                enabled = false;
            } else {
                enabled = true;
            }
        } else {
            enabled = false;
        }
    }
}
